<!-- TranslationComponent.vue -->
<template>
  <div class="translation-component">
    <!-- 翻译选项 -->
    <div class="translation-options">
      <div class="setting-item">
        <div class="setting-label">目标语言:</div>
        <t-select
          v-model="selectedLanguage"
          placeholder="选择翻译目标语言"
          class="setting-select"
        >
          <t-option
            v-for="language in targetLanguages"
            :key="language.code"
            :value="language.code"
            :label="language.name"
          >
            {{ language.name }}
          </t-option>
        </t-select>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="translation-actions">
      <t-button
        theme="primary"
        :loading="isTranslating"
        :disabled="isTranslating || selectedItems.length === 0"
        @click="translateSelected"
      >
        {{ isTranslating ? '翻译中...' : '翻译选中' }}
      </t-button>

      <t-button
        theme="success"
        :loading="isTranslating"
        :disabled="isTranslating || textItems.length === 0"
        @click="translateAll"
      >
        {{ isTranslating ? '翻译中...' : '翻译全部' }}
      </t-button>
    </div>

    <!-- 翻译进度展示 -->
    <div class="translation-progress" v-if="isTranslating">
      <t-progress :percentage="progressPercentage" :label="progressLabel" status="active" />
    </div>
  </div>
</template>
<script setup>
import { ref, computed } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
// 导入翻译API
import { translateText } from '@renderer/api/translateApi';

const props = defineProps({
  // 文本项列表
  textItems: {
    type: Array,
    required: true
  },
  // 已选择的项目ID列表
  selectedItems: {
    type: Array,
    required: true
  }
});

const emit = defineEmits(['update:items']);

// 可选的目标语言
const targetLanguages = [
  { code: 'zh-CN', name: '中文（简体）' },
  { code: 'en', name: '英语' },
  { code: 'th', name: '泰语' },
  { code: 'vi', name: '越南语' }
];

// 选择的目标语言
const selectedLanguage = ref('zh-CN');

// 翻译状态
const isTranslating = ref(false);
const currentIndex = ref(0);
const totalItemsToTranslate = ref(0);

// 计算翻译进度百分比
const progressPercentage = computed(() => {
  if (totalItemsToTranslate.value === 0) return 0;
  return Math.round((currentIndex.value / totalItemsToTranslate.value) * 100);
});

// 计算翻译进度标签
const progressLabel = computed(() => {
  return `${currentIndex.value}/${totalItemsToTranslate.value}`;
});

// 翻译选中项目的方法
const translateSelected = async () => {
  if (props.selectedItems.length === 0) {
    MessagePlugin.warning('请先选择需要翻译的文本');
    return;
  }

  // 获取选中的项目
  const itemsToTranslate = props.textItems.filter(item => props.selectedItems.includes(item.id));
  await startTranslation(itemsToTranslate);
};

// 翻译所有项目的方法
const translateAll = async () => {
  if (props.textItems.length === 0) {
    MessagePlugin.warning('没有可翻译的文本');
    return;
  }

  await startTranslation([...props.textItems]);
};

// 启动翻译过程
const startTranslation = async (items) => {
  if (isTranslating.value) return;

  try {
    isTranslating.value = true;
    currentIndex.value = 0;
    totalItemsToTranslate.value = items.length;

    // 创建一个新的数组来保存所有项目（包括已翻译和未翻译的）
    const updatedItems = [...props.textItems];

    // 逐个翻译项目
    for (const item of items) {
      // 更新计数器
      currentIndex.value++;

      try {
        // 翻译标题和内容
        const [translatedName, translatedText] = await Promise.all([
          item.name ? translateText(item.name, 'auto', selectedLanguage.value) : Promise.resolve(item.name),
          translateText(item.text, 'auto', selectedLanguage.value)
        ]);

        // 在原始数组中找到并更新该项目
        const itemIndex = updatedItems.findIndex(i => i.id === item.id);
        if (itemIndex !== -1) {
          updatedItems[itemIndex] = {
            ...updatedItems[itemIndex],
            name: translatedName || updatedItems[itemIndex].name,
            text: translatedText,
            translated: true
          };
        }
      } catch (error) {
        console.error(`翻译项目 ID: ${item.id} 失败:`, error);
        MessagePlugin.error(`翻译失败: ${error.message || '未知错误'}`);
      }
    }

    // 将更新后的项目列表发送回父组件
    emit('update:items', updatedItems);

    MessagePlugin.success(`翻译完成，已翻译 ${items.length} 个文本`);
  } catch (error) {
    console.error('翻译过程出错:', error);
    MessagePlugin.error('翻译过程出错: ' + (error.message || '未知错误'));
  } finally {
    isTranslating.value = false;
  }
};
</script>

<style scoped>
.translation-component {
  margin-bottom: 16px;
  padding: 16px;
  border-radius: 8px;
  background-color: #f9f9f9;
  border: 1px dashed #ddd;
}

.translation-options {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 16px;
}

.setting-item {
  flex: 1;
  min-width: 200px;
}

.setting-label {
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}

.setting-select {
  width: 100%;
}

.translation-actions {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.translation-progress {
  margin-top: 16px;
}
</style>
